package leetcode

import "gitee.com/ombak/leetcode/pkg/strings"

func reverse(s string) string {
	res := ""
	for _, v := range s {
		res = string(v) + res
	}
	return res
}

// https://leetcode.com/problems/reverse-words-in-a-string/
func reverseWords(s string) string {
	// remove extra space character
	clear := strings.Clear(s)
	if clear == "" {
		return clear
	}
	if clear[len(clear)-1:] == " " {
		clear = clear[:len(clear)-1]
	}
	// reverse the string s entirely
	reverse1 := reverse(clear)
	// reverse each word
	left, right := 0, 0
	reverse2 := ""
	for ; right < len(reverse1); right++ {
		if reverse1[right:right+1] == " " {
			reverse2 += reverse(reverse1[left:right]) + " "
			left = right + 1
		} else if right == len(reverse1)-1 {
			reverse2 += reverse(reverse1[left : right+1])
		}
	}
	return reverse2
}
